import React, { Component } from 'react'
import commonTypes from '../../utils/commonTypes'
import PropTypes from 'prop-types'
import withDataList from '../../HOC/withDataList'

class CheckBox extends Component {

    static propTypes = {
        value: commonTypes.choosedDatas,
        optionItem: commonTypes.optionItem.isRequired,
        name: PropTypes.string.isRequired,
        onChange: PropTypes.func,
    }

    onChange = (e) => {
        let newArr = []
        if (e.target.checked) {
            newArr = [...this.props.value, e.target.value]
        } else {
            newArr = this.props.value.filter(item => item !== e.target.value)
        }
        this.props.onChange && this.props.onChange(newArr)
    }

    render() {
        const { value, optionItem, name } = this.props
        return <label>
            <input
                type="checkbox"
                name={name}
                value={optionItem.value}
                checked={value.includes(optionItem.value)}
                onChange={this.onChange}
            />
            {optionItem.label}
        </label>
    }
}

/**
 * 一组多选框
 */
export default withDataList(CheckBox)
